#!/bin/bash
DOMAIN_URL=$1
DB_HOST=$2
DB_PWD=$3
REDIS_HOST=$4
REDIS_PWD=$5
OBS_BUCKETNAME=$6
CSS_HOST=$7
CSS_PWD=$8
ACCESS_KEY=$9
SECRET_KEY=${10}
PROJECT_ID=${11}


#python环境>=3.7 ECS版本默认3.6
#更换版本后ssl配置需要改
wget -O /etc/yum.repos.d/CentOS-Base.repo https://repo.huaweicloud.com/repository/conf/CentOS-7-reg.repo
yum clean all
yum makecache
cd ~ || exit
wget -c https://mirrors.huaweicloud.com/python/3.7.2/Python-3.7.2.tgz
tar -zxvf Python-3.7.2.tgz -C ./
mv Python-3.7.2 python3
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel libffi-devel
cd python3 || exit
./configure
#./configure --prefix=/usr/local/python3 \--with-openssl=/usr/bin/openssl --enable-optimizations
make & make install
ln -snf /usr/local/bin/python3.7 /usr/bin/python3
ln -snf /usr/local/bin/pip3.7 /usr/bin/pip3

#换pip源
mkdir ~/.pip
cat > ~/.pip/pip.conf <<- EOF
[global]
index-url = https://mirrors.huaweicloud.com/repository/pypi/simple
trusted-host = mirrors.huaweicloud.com
timeout = 120
EOF

#step up back environment
yum -y install git
cd /usr/local || exit
git clone https://gitee.com/HuaweiCloudDeveloper/huaweicloud-solution-ploto.git


cat > /usr/local/huaweicloud-solution-ploto/ploto/conf/conf.py <<-EOF
# 加密秘钥，base64字符串格式
aes_gcm_key = '**********************'

# mysql数据库登录配置
mysql_user = "root"
mysql_pwd = "******************"
mysql_aes_gcm_iv = "******************"
mysql_aes_gcm_tag = "******************"

obs_ak = "${ACCESS_KEY}"
obs_sk = "${SECRET_KEY}"
obs_endpoint = "https://obs.cn-north-4.myhuaweicloud.com"

data_mgt_apis_domain = "https://data.holomatic.com"
data_mgt_apis = {
    "bags_add": data_mgt_apis_domain + "/api/bags/add",
    "bags_detail": data_mgt_apis_domain + "/api/bags/detail",
    "bags_list": data_mgt_apis_domain + "/api/bags/search",
    "scenario_bag_detail": data_mgt_apis_domain + "/api/scenario_bag/detail",
    "scenario_bag_list": data_mgt_apis_domain + "/api/scenario_bag/search",
    "scene_cut": data_mgt_apis_domain + "/api/task/cut_scene",
    "scene_cut_task_detail": data_mgt_apis_domain + "/api/task/detail",
    "scene_cut_task_cancel": data_mgt_apis_domain + "/api/task/cancel",
    "scene_cut_task_log": data_mgt_apis_domain + "/api/task/log"
}

obs_bucket_name = "${OBS_BUCKETNAME}"
anonymized_data_url = "http://localhost:8000/data/anonymized"
scene_data_url = "http://localhost:8000/data/scene"

ces_ak = obs_ak
ces_sk = obs_sk
ces_endpoint = "'https://ces.cn-north-4.myhuaweicloud.com"
ces_project_id = "${PROJECT_ID}"
EOF
cat > /usr/local/huaweicloud-solution-ploto/ploto/ploto/settings/dev.py <<-EOF
ALLOWED_HOSTS = ["*"]
SESSION_COOKIE_SAMESITE = None
CSRF_COOKIE_SAMESITE = None
DEBUG = True
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "ploto",
        "USER": "root",
        "PASSWORD": "${DB_PWD}",
        "HOST": "${DB_HOST}",
        "PORT": "3306",
    },
    # 'slave': {
    #    "ENGINE": "django.db.backends.mysql",
    #    #"NAME": "dashboard",
    #    "NAME": "dashboard_test",
    #    "USER": "root",
    #    "PASSWORD": settings_password,
    #    "HOST": "*********",
    #    "PORT": "3306",
    # }
}
ES_CLUSTER = '${CSS_HOST}'
ES_USERNAME = 'admin'
ES_PASSWORD = '${CSS_PWD}'
ES_HOST = ES_CLUSTER.split(',')[0]

ELASTICSEARCH_DSL={
    'default':{
        'hosts': f'https://{ES_HOST}',
        'http_auth':f'{ES_USERNAME}:{ES_PASSWORD}',
        'verify_certs': False
    }
}

REDIS_HOST = '${REDIS_HOST}'
REDIS_PORT = '6379'
REDIS_PASSWORD = '${REDIS_PWD}'

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://" + REDIS_HOST + ":" +
                    REDIS_PORT + "/9",
        "TIMEOUT": 3600 * 60,  # 缓存的有效时间(s)
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {
                "max_connections": 100
            },
            "PASSWORD": REDIS_PASSWORD,
        }
    }
}

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
SESSION_COOKIE_AGE = 60 * 60  # session的有效时间(s)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_SAVE_EVERY_REQUEST = True

BROKER_URL = 'redis://:' + REDIS_PASSWORD + \
             '@' + REDIS_HOST + ':' + REDIS_PORT + '/0'
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600}
CELERY_RESULT_BACKEND = 'redis://:' + REDIS_PASSWORD + \
                        '@' + REDIS_HOST + ':' + REDIS_PORT + '/0'
CELERY_RESULT_BACKEND = 'django-db'
EOF
cat > /usr/local/huaweicloud-solution-ploto/initutils/conf/conf.py <<-EOF
import sys
sys.path.append("..")
from ploto.conf.conf import obs_ak, obs_sk, obs_endpoint

# mysql数据库登录配置
DBHost = "${DB_HOST}"
DBPort = 3306
DBUser = "root"
DBPassword = "${DB_PWD}"
DBName = "ploto"

# obs接入配置
ObsAK = obs_ak
ObsSK = obs_sk
ObsEndpoint = obs_endpoint

# obs文件配置 objectname以逗号分割， 存储类型为标准、低频、归档， Times为文件填充的倍数， Dir默认为当前initutils目录
BucketName = "${OBS_BUCKETNAME}"
ObjectName = "scene,anonymize"
StorageClass = "STANDARD"
Times = 5
FileDir = "ploto_file"

EOF
cat > /usr/local/huaweicloud-solution-ploto/config/env.js <<-EOF
const BASE_URL = ''
export default {
  BASE_URL
}
EOF
cat > /usr/local/huaweicloud-solution-ploto/vue.config.js <<-EOF
module.exports = {
  // baseUrl: '/',
  publicPath: '/',

  outputDir: 'dist',
  assetsDir: 'assets',
  runtimeCompiler: true,
  productionSourceMap: true,
  parallel: true,

  css: {
    // 是否提取css 生产环境可以配置为 true
    extract: false
  },

  devServer: {
    host: '${DOMAIN_URL}',
    port: '80',
    open: true
  },
  lintOnSave: false
}
EOF
pip3 install --upgrade pip
while [ ! -d "/usr/local/lib/python3.7/site-packages/django/" ]
do
	pip3 install django==3.2.12
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/crypto/" ]
do
	pip3 install crypto
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/Crypto/" ]
do
	pip3 install pycryptodome
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/corsheaders/" ]
do
	pip3 install django-cors-headers
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/rest_framework/" ]
do
	pip3 install djangorestframework
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/pymysql/" ]
do
	pip3 install pymysql
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/django_extensions/" ]
do
	pip3 install django_extensions
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/django_celery_results/" ]
do
	pip3 install django_celery_results
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/openpyxl/" ]
do
	pip3 install openpyxl
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/celery/" ]
do
	pip3 install celery
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/django_celery_beat/" ]
do
	pip3 install django-celery-beat
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/eventlet/" ]
do
	pip3 install eventlet
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/django_redis/" ]
do
	pip3 install django-redis
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/django_elasticsearch_dsl/" ]
do
	pip3 install django_elasticsearch_dsl==7.2.2
done

pip3 install --upgrade elasticsearch==7.13.0

while [ ! -d "/usr/local/lib/python3.7/site-packages/numpy/" ]
do
	pip3 install numpy
done
#obs sdk
while [ ! -d "/usr/local/lib/python3.7/site-packages/obs/" ]
do
	pip3 install esdk-obs-python --trusted-host pypi.org
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/huaweicloudsdkcore/" ]
do
	pip3 install huaweicloudsdkcore
done

while [ ! -d "/usr/local/lib/python3.7/site-packages/huaweicloudsdkces/" ]
do
	pip3 install huaweicloudsdkces
done

#step up front environment
# install nodejs
cd /usr/lib || exit
mkdir node
cd node || exit
wget -c https://repo.huaweicloud.com/nodejs/v16.16.0/node-v16.16.0-linux-x64.tar.xz
tar xf node-v16.16.0-linux-x64.tar.xz
cd node-v16.16.0-linux-x64 || exit
ln -s /usr/lib/node/node-v16.16.0-linux-x64/bin/npm /usr/local/bin/
ln -s /usr/lib/node/node-v16.16.0-linux-x64/bin/node /usr/local/bin/

# deploy npm
npm config set registry https://repo.huaweicloud.com/repository/npm/
# npm cache clean -f


# install nginx
wget -c http://nginx.org/download/nginx-1.20.2.tar.gz
tar -xvf nginx-1.20.2.tar.gz
cd nginx-1.20.2 || exit
./configure --with-http_stub_status_module --with-http_ssl_module
make && make install

# 注意工程绝对路径
cat > /usr/local/nginx/conf/nginx.conf << EOF

user  root;
worker_processes  2;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
    #                  '\$status \$body_bytes_sent "\$http_referer" '
    #                  '"\$http_user_agent" "\$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root /usr/local/huaweicloud-solution-ploto/dist/;
            index  index.html index.htm;
            try_files \$uri \$uri/ /index.html;
	}
        #   指定允许跨域的方法，*代表所有
        add_header Access-Control-Allow-Methods *;

        #   预检命令的缓存，如果不缓存每次会发送两次请求
        add_header Access-Control-Max-Age 3600;
        #   带cookie请求需要加上这个字段，并设置为true
        add_header Access-Control-Allow-Credentials true;

        #   表示允许这个域跨域调用（客户端发送请求的域名和端口）
        #   \$http_origin动态获取请求客户端请求的域   不用*的原因是带cookie的请求不支持*号
        add_header Access-Control-Allow-Origin \$http_origin;

        #   表示请求头的字段 动态获取
        add_header Access-Control-Allow-Headers
        \$http_access_control_request_headers;


        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header x-requested-with XMLHttpRequest;
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
		
        location /login{
            proxy_pass http://localhost:8000;
        }
        
        location /monitor{
            proxy_pass http://localhost:8000;
        }
        
        location /data{
            proxy_pass http://localhost:8000;
        }
        
         location /ADlogin{
            proxy_pass http://localhost:8000;
        }
        
        location /logout{
            proxy_pass http://localhost:8000;
        }
		
		location /admin{
            proxy_pass http://localhost:8000;
        }
        
        location /trace{
            proxy_pass http://localhost:8000;
        }
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts\$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    server {
        listen       81;
        server_name  localhost;
        
        location / {
            root /home/all_code/dist/;
            index  index.html index.htm;
            try_files \$uri \$uri/ /index.html;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
EOF

cd /usr/local || exit
mkdir shelllist
cd shelllist || exit
wget -c https://documentation-samples.obs.myhuaweicloud.com/solution-as-code-publicbucket/solution-as-code-moudle/ploto-based-autonomous-driving-platform/userdata/celery.sh
wget -c https://documentation-samples.obs.myhuaweicloud.com/solution-as-code-publicbucket/solution-as-code-moudle/ploto-based-autonomous-driving-platform/userdata/beat.sh

cd /usr/local/huaweicloud-solution-ploto/ploto || exit
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py makemigrations user
python3 manage.py migrate user
python3 manage.py makemigrations data_mgt
python3 manage.py migrate data_mgt
python3 manage.py makemigrations monitor
python3 manage.py migrate monitor
python3 manage.py makemigrations ae_trace
python3 manage.py migrate ae_trace

python3 manage.py shell <<EOF
from django.contrib.auth.models import User
user = User.objects.create_user('ploto','','ploto1234', is_superuser = True, is_staff=True)
exit()
EOF

cd /usr/local/huaweicloud-solution-ploto || exit
npm install
npm run build

cd /usr/local/nginx/sbin || exit
pkill -9 nginx
./nginx
sh /usr/local/shelllist/beat.sh &
sh /usr/local/shelllist/celery.sh &

cd /usr/local/huaweicloud-solution-ploto/ploto || exit
python3 manage.py runserver 0.0.0.0:8000
